import 'dart:collection';

import 'package:FineArt/core/api/home_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/utils/event.dart';
import 'package:FineArt/core/widget/web_view_page.dart';
import 'package:FineArt/core/widget/web_view_page_new.dart';
import 'package:FineArt/page/tab/recommend/RecommendItemMore.dart';
import 'package:FineArt/page/tab/recommend/component/recommendItem.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_page_indicator/flutter_page_indicator.dart';

class RecommendMainPage extends StatefulWidget {
  List<Module> modules = [];
  RecommendMainPage({this.modules});
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _RecommendPageState();
  }
}

class _RecommendPageState extends State<RecommendMainPage> {
  final List<HomeBanner> banners = new List();
  final List<Works> works = new List();
  final List<Techart> techarts = new List();
  final List<Tutor> tutors = new List();
  List<Resource> resources1 = [];
  List<Resource> resources2 = [];
  List<Resource> resources3 = [];
  var titles = ["优秀作业", "课堂范画", "教师展示"];
  // var types = ["works", "techart", "tutor"];
  var types = ["module", "module", "module"];
  void _getBanners() {
    HomeApi().banners().then((banner_res) {
      if (banner_res.code == 200) {
        setState(() {
          banners.clear();
          banners.addAll(banner_res.data);
        });
      }
    });
  }

  void _getWorks(pg, size) {
    HomeApi().works(pg, size).then((res) {
      // if (res.code == 200) {
      //   setState(() {
      //     works.clear();
      //     for (WorksGroup group in res.data.list) {
      //       if (group.items != null && group.items.isNotEmpty) {
      //         works.addAll(group.items);
      //       }
      //     }
      //   });
      // }
      _getModuleData(widget.modules[0].id.toString(), 1);
    });
  }

  void _getTecharts(pg, size) {
    // HomeApi().techarts(pg, size).then((res) {
    //   if (res.code == 200) {
    //     setState(() {
    //       techarts.clear();
    //       for (TechartGroup group in res.data.list) {
    //         if (group.items != null && group.items.isNotEmpty) {
    //           techarts.addAll(group.items);
    //         }
    //       }
    //     });
    //   }
    // });
    _getModuleData(widget.modules[1].id.toString(), 2);
  }

  void _getTutors(pg, size) {
    // HomeApi().teachers(pg, size).then((res) {
    //   if (res.code == 200) {
    //     setState(() {
    //       tutors.clear();
    //       tutors.addAll(res.data.list);
    //     });
    //   }
    // });
    _getModuleData(widget.modules[2].id.toString(), 3);
  }
  _initModuleData(){
    for(int i=0;i<titles.length;i++){
      titles[i]=widget.modules[i].section+"推荐";
    }

  }
  _getModuleData(String moduleId,int index){
    ModuleApi().search(moduleId, "", 1, 3).then((res) {
      if (!this.mounted) return;
      List<Resource> rowList =res.data.list;
      LogUtil.d("$index rowList length:"+rowList.length.toString());
      if(rowList.length>3){
        rowList = rowList.sublist(0,3);
        LogUtil.d("rowList length:"+rowList.length.toString());
      }
      setState(() {
        switch(index){
          case 1:
            resources1.clear();
            resources1.addAll(rowList);
            break;
          case 2:
            resources2.clear();
            resources2.addAll(rowList);
            break;
          case 3:
            resources3.clear();
            resources3.addAll(rowList);
            break;
        }
      });

      if(index==3){
        _finishLoader();
      }
    });
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initModuleData();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getBanners();
    _getWorks(-1, 3);
    _getTecharts(-1, 3);
    _getTutors(-1, 3);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: _buildEasyRefresh()
      ),
    );
  }

  EasyRefreshController _easyRefreshController=new EasyRefreshController();
 Widget _buildEasyRefresh(){
   EasyRefresh _easyRefresh = EasyRefresh.custom(
      header:
      MaterialHeader(completeDuration: new Duration(milliseconds: 100)),
      footer: MaterialFooter(),
      controller: _easyRefreshController,
      onRefresh: () async {
        _getBanners();
        _getWorks(-1, 3);
        _getTecharts(-1, 3);
        _getTutors(-1, 3);

      },
      onLoad: () async {


      },
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate(
                (context, index) {
              if (index == 0) return getBannerWidget();
              // var lists = [this.works, this.techarts, this.tutors];
              var lists = [this.resources1, this.resources2, this.resources3];
              return RecommendItem(
                  title: titles[index - 1],
                  type: types[index - 1],
                  list: lists[index - 1],
                  moreClick: () {
                    // if (index == 3) return; //teacher
                    LogUtil.d("recommend more click");
                    XEvent.post("tabIndex",index);
                    // Navigator.of(context)
                    //     .push(MaterialPageRoute(builder: (context) {
                    //   return RecommendItemMore(
                    //       titles[index - 1], types[index - 1]);
                    // }));
                  });
            },
            childCount: 4,
          ),
        ),
      ],
    );
    return _easyRefresh;
  }
  Widget getBannerWidget() {
    return Container(
      height: getPortraitSHeight(117.5),
      width: getPortraitSWidth(330),
      padding: EdgeInsets.symmetric(horizontal: getPortraitSWidth(5),vertical: getPortraitSHeight(5)),
      child: Swiper(
        autoplay: true,
        duration: 2000,
        autoplayDelay: 5000,
        loop: false,
        itemBuilder: (context, index) {
          return ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image(
                fit: BoxFit.fill,
                image: CachedNetworkImageProvider(
                  banners[index].url,
                ),
              ));
        },
        onTap: (index) {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return WebViewPageNew(banners[index].linkurl, "");
          }));
        },
        //itemCount: urls.length,
        itemCount: banners.length,
        indicatorLayout: PageIndicatorLayout.SLIDE,
        pagination: SwiperPagination(builder: DotSwiperPaginationBuilder(size: 6)),
      ),
    );
  }

  _finishLoader() async{

    await Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        // 控制器关闭加载功能，还可以设置没有更多数据noMore，可以根据需求自己变更，这里同样也需要在数据请求成功进行关闭。
        _easyRefreshController.finishLoad(success: true,noMore: true);
        LogUtil.d("finishLoad>>>>>>>>>>>>>>>>>");
      });
    });


  }
}
